package com.starblink.android.guang.push

import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.ktx.messaging
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.log.SKLogger
import com.starblink.rocketreserver.FirebaseReportQuery
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Firebase消息推送实用工具
 */
object FCMUtils {
    const val KEY_XROUTE = "xRoute"
    const val showLog = true

    /**
     * 将FcmToken同步到服务器
     * @note 异步执行
     */
    fun syncFcmToken() {
        SKLogger.e("dss", "syncFcmToken", showLog)
        CoroutineScope(Dispatchers.IO).launch {
            Firebase.messaging.token.addOnCompleteListener(OnCompleteListener { task ->
                if (!task.isSuccessful) {
                    SKLogger.e("dss", "获取Fcm Token失败：${task.exception}", showLog)
                    return@OnCompleteListener
                }
                val newFcmToken = task.result
                if (newFcmToken.isNullOrEmpty()) {
                    SKLogger.e("dss", "获取Fcm Token失败,Token为null", showLog)
                    return@OnCompleteListener
                }
                SKLogger.e("dss", "获取Fcm Token成功=$newFcmToken")

                CoroutineScope(Dispatchers.IO).launch {
                    val response = SkGqlClient.skQuery(
                        FirebaseReportQuery(
                            firebaseId = newFcmToken
                        )
                    )
                    if (response?.data != null && response.data!!.firebaseReport == true) {
                        SKLogger.e("dss", "syncFcmToken成功", showLog)
                    } else {
                        SKLogger.e("dss", "syncFcmToken失败", showLog)
                    }
                }
            })
        }
    }
}